﻿using System.Web.UI;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Net;
using System.Web;
using System.Web.Security;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Threading;
using System.IO;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;

namespace DGSFramework
{
    public class Globals : Page
    {
        public Globals()
        {
        }

        /// <summary>
        /// Rewrite duong dan
        /// </summary>
        /// <param name="str">chuoi can rewrite</param>
        /// <returns></returns>
        public static string FriendlyURL(string str)
        {
            return FriendlyURL(str, false);
        }
        /// <summary>
        /// Chọn ngày để lấy dữ liệu, ngay chu nhật và thứ 2 sẽ xem dữ liệu của ngày thứ 6 trước đó
        /// </summary>
        /// <returns></returns>
        public static DateTime DateGetData()
        {
            var dayOfWeek = DateTime.Now.DayOfWeek.ToString().ToLower();
            var currentDate = DateTime.Now.AddDays(-1).Date;
            if (dayOfWeek == "sunday")
                currentDate = DateTime.Now.AddDays(-2).Date;
            else if (dayOfWeek == "monday")
                currentDate = DateTime.Now.AddDays(-3).Date;
            return currentDate;

        }
        /// <summary>
        /// Rewrite duong dan
        /// </summary>
        /// <param name="str">chuoi can rewrite</param>
        /// <param name="toLowerCase">true: chuoi duong dan viet thuong</param>
        /// <returns></returns>
        public static string FriendlyURL(string str, bool toLowerCase)
        {
            string stFormD = str.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }

            str = (sb.ToString().Normalize(NormalizationForm.FormC));
            //Replace . with - hyphen
            str = Regex.Replace(str.Trim(), @"\W", "-");

            //Replace multiple "-" hyphen with single "-" hyphen.
            str = Regex.Replace(str, @"\055+", "-").Trim('-');
            str = Regex.Replace(str, @"đ", "d");
            str = Regex.Replace(str, @"Đ", "D");

            if (toLowerCase)
                return str.ToLower();
            else
                return str;

        }

        /// <summary>
        /// Rewrite duong dan
        /// </summary>
        /// <param name="str">chuoi can rewrite</param>
        /// <returns></returns>
        public static string FriendlyURL(object str)
        {
            return FriendlyURL(str.ToString());
        }

        /// <summary>
        /// Rewrite duong dan
        /// </summary>
        /// <param name="str">chuoi can rewrite</param>
        /// <param name="toLowerCase">true: chuoi duong dan viet thuong</param>
        /// <returns></returns>
        public static string FriendlyURL(object str, bool toLowerCase)
        {
            return FriendlyURL(str.ToString(), toLowerCase);
        }

        /// <summary>
        /// Kiem tra file co dung dinh dang anh hay ko
        /// </summary>
        /// <param name="ImageName">ten co phan mo rong cua file</param>
        /// <returns></returns>
        public static bool CheckExtensionImage(string ImageName)
        {
            string strExtension = System.IO.Path.GetExtension(ImageName).ToUpper();
            if (strExtension == ".JPG" || strExtension == ".GIF" || strExtension == ".JPEG" || strExtension == ".PNG" || strExtension == ".SWF" || strExtension == ".BMP" || strExtension == ".ICO")
                return true;
            else
                return false;
        }

        /// <summary>
        /// Loai bo dau tieng viet
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSign4VietnameseString(string str)
        {
            string stFormD = str.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }

            str = (sb.ToString().Normalize(NormalizationForm.FormC));

            str = Regex.Replace(str, @"đ", "d");
            str = Regex.Replace(str, @"Đ", "D");

            return str;
        }

        /// <summary>
        /// Lay Ip cua server
        /// </summary>
        /// <returns></returns>
        public static string GetServerIP()
        {
            string strHostName = "";
            strHostName = System.Net.Dns.GetHostName();

            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

            IPAddress[] addr = ipEntry.AddressList;

            return addr[addr.Length - 1].ToString();
        }

        /// <summary>
        /// Lay Ip cua client
        /// </summary>
        /// <returns></returns>
        public static string GetClientIPAddress()
        {
            string ip;
            try
            {
                ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(ip))
                {
                    if (ip.IndexOf(",") > 0)
                    {
                        string[] ipRange = ip.Split(',');
                        int le = ipRange.Length - 1;
                        ip = ipRange[le];
                    }
                }
                else
                {
                    ip = HttpContext.Current.Request.UserHostAddress;
                }
            }
            catch { ip = null; }
            return ip;
        }

        /// <summary>
        /// encode base64
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        /// <summary>
        /// decode base64
        /// </summary>
        /// <param name="base64EncodedData"></param>
        /// <returns></returns>
        public static string Base64Decode(string base64EncodedData)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }

        /// <summary>
        /// ma hoa chuoi chuan md5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncryptMD5(string str)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }

        /// <summary>
        /// ma hoa chuoi chuan sha1
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncryptSHA1(string str)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");
        }

        /// <summary>
        /// kiem tra xem dang dung ngon ngu viet nam
        /// </summary>
        /// <returns></returns>
        public static bool IsLanguageVN()
        {
            string currentLanguage = HttpContext.Current.Session["language"] == null ? "vi-VN" : HttpContext.Current.Session["language"].ToString();
            if (currentLanguage == "vi-VN")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// lay ngon ngu
        /// </summary>
        /// <param name="strVN"></param>
        /// <param name="strEN"></param>
        /// <returns></returns>
        public static string GetLanguage(string strVN, string strEN, bool viFrist)
        {
            string currentLanguage;
            if (viFrist == false)
                currentLanguage = HttpContext.Current.Session["language"] == null ? "en-US" : HttpContext.Current.Session["language"].ToString();
            else
                currentLanguage = HttpContext.Current.Session["language"] == null ? "vi-VN" : HttpContext.Current.Session["language"].ToString();
            switch (currentLanguage)
            {
                case "vi-VN":
                    return strVN;
                case "en-US":
                    return strEN;
                default:
                    return currentLanguage;
            }
        }

        /// <summary>
        /// lay ngon ngu
        /// </summary>
        /// <param name="strVN"></param>
        /// <param name="strEN"></param>
        /// <returns></returns>
        public static string GetLanguage(object strVN, object strEN, bool viFrist)
        {
            return GetLanguage(strVN == null ? "" : strVN.ToString(), strEN == null ? "" : strEN.ToString(), viFrist);
        }

        /// <summary>
        /// lay duong dan goc website
        /// </summary>
        public static string ApplicationPath
        {
            get
            {
                string url = HttpContext.Current.Request.ApplicationPath;
                if (url.EndsWith("/"))
                    return url;
                else
                    return url + "/";
            }
        }

        /// <summary>
        /// lay duong dan goc website toi file
        /// </summary>
        /// <returns></returns>
        public static string PhysicalApplicationPath()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath.ToString();
        }

        /// <summary>
        /// tao ra ten file ko bi trung ten
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetFileName(string fileName)
        {
            string strFileName;
            strFileName = DateTime.Now.Day.ToString() +
            DateTime.Now.Month.ToString() +
            DateTime.Now.Year.ToString() +
            DateTime.Now.Hour.ToString() +
            DateTime.Now.Minute.ToString() +
            DateTime.Now.Second.ToString() +
            DateTime.Now.Millisecond.ToString() + fileName;
            return strFileName;
        }

        /// <summary>
        /// resize anh
        /// </summary>
        /// <param name="src"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <returns></returns>
        public static Bitmap ProportionallyResizeBitmap(Bitmap src, int maxWidth, int maxHeight)
        {
            // original dimensions
            int w = src.Width;
            int h = src.Height;

            // Longest and shortest dimension
            int longestDimension = (w > h) ? w : h;
            int shortestDimension = (w < h) ? w : h;

            // propotionality
            float factor = ((float)longestDimension) / shortestDimension;

            // default width is greater than height
            double newWidth = maxWidth;
            double newHeight = maxWidth / factor;

            // if height greater than width recalculate
            if (w < h)
            {
                newWidth = maxHeight / factor;
                newHeight = maxHeight;
            }
            if (newHeight > maxHeight)
            {
                newHeight = maxHeight;
            }

            // Create new Bitmap at new dimensions
            Bitmap result = new Bitmap((int)newWidth, (int)newHeight);
            using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
                g.DrawImage(src, 0, 0, (int)newWidth, (int)newHeight);
            return result;
        }

        /// <summary>
        /// tao wartermark image
        /// </summary>
        /// <param name="file"></param>
        /// <param name="scrImageUploadPath"></param>
        /// <param name="srcWatermarkPath"></param>
        public static void CreateWatermark(HttpPostedFile file, string scrImageUploadPath, string srcWatermarkPath)
        {
            string strFilePath = ConfigPaths.Path_ImageUploadTemp_Folder_MapPath + "watermark_photo.jpg";
            // create tmp file
            file.SaveAs(HttpContext.Current.Server.MapPath(strFilePath));

            //create a image object containing the photograph to watermark
            System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(strFilePath));
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //load the Bitmap into a Graphics object 
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //create a image object containing the watermark
            System.Drawing.Image imgWatermark = new Bitmap(srcWatermarkPath);
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            //------------------------------------------------------------
            //Step #1 - filter image
            //------------------------------------------------------------

            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //Draws the photo Image object at original size to the graphics object.
            grPhoto.DrawImage(
                imgPhoto,                               // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw. 
                0,                                      // y-coordinate of the portion of the source image to draw. 
                phWidth,                                // Width of the portion of the source image to draw. 
                phHeight,                               // Height of the portion of the source image to draw. 
                GraphicsUnit.Pixel);                    // Units of measure 

            //------------------------------------------------------------
            //Step #2 - Insert Watermark image
            //------------------------------------------------------------

            //Create a Bitmap based on the previously modified photograph Bitmap
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color 
            //manipulations by defineing a ImageAttributes object and 
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //The first step in manipulating the watermark image is to replace 
            //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
            //to do this we will use a Colormap and use this to define a RemapTable
            ColorMap colorMap = new ColorMap();

            //My watermark was defined with a background of 100% Green this will
            //be the color we search for and replace with transparency
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //The second color manipulation is used to change the opacity of the 
            //watermark.  This is done by applying a 5x5 matrix that contains the 
            //coordinates for the RGBA space.  By setting the 3rd row and 3rd column 
            //to 0.3f we achive a level of opacity
            float[][] colorMatrixElements = { 
												new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},       
												new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},        
												new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},        
												new float[] {0.0f,  0.0f,  0.0f,  1.0f, 0.0f},        
												new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}};
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                ColorAdjustType.Bitmap);

            //For this example we will place the watermark in the upper right
            //hand corner of the photograph. offset down 10 pixels and to the 
            //left 10 pixles

            int xPosOfWm = ((phWidth - wmWidth) - 10);
            int yPosOfWm = ((phHeight - wmHeight) - 10);

            grWatermark.DrawImage(imgWatermark,
                new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight),  //Set the detination Position
                0,                  // x-coordinate of the portion of the source image to draw. 
                0,                  // y-coordinate of the portion of the source image to draw. 
                wmWidth,            // Watermark Width
                wmHeight,		    // Watermark Height
                GraphicsUnit.Pixel, // Unit of measurment
                imageAttributes);   //ImageAttributes Object

            //Replace the original photgraphs bitmap with the new Bitmap
            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //save new image to file system.
            imgPhoto.Save(scrImageUploadPath, ImageFormat.Jpeg);


            imgPhoto.Dispose();
            imgWatermark.Dispose();
        }

        /// <summary>
        /// Xoa nhieu ky tu thua
        /// </summary>
        /// <param name="OriginalText">chuoi truyen vao</param>
        /// <param name="MultipeString">ky tu thua muon xoa</param>
        /// <returns></returns>
        public static string RemoveMultipeString(string OriginalText, string MultipeString)
        {
            while (OriginalText.IndexOf(MultipeString + MultipeString) != -1)
            {
                OriginalText = OriginalText.Replace(MultipeString + MultipeString, MultipeString);
            }
            return OriginalText;
        }

        /// <summary>
        /// tao chuoi bat ki
        /// </summary>
        /// <param name="numChars">so ky tu muon tao ra</param>
        /// <returns></returns>
        public static string GetRandomString(int numChars)
        {
            string chars = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            Random rnd = new Random();
            string random = string.Empty;
            for (int i = 0; i < numChars; i++)
            {
                random += chars.Substring(rnd.Next(0, chars.Length), 1);
            }
            return random;
        }

        protected override void InitializeCulture()
        {
            Session["language"] = Session["language"] == null ? "vi-VN" : Session["language"];

            string cul = Session["language"].ToString();

            Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);

            Thread.CurrentThread.CurrentCulture = new CultureInfo(cul);
        }

        /// <summary>
        /// cat chuoi loai bo html
        /// </summary>
        /// <param name="str"></param>
        /// <param name="lenght"></param>
        /// <returns></returns>
        public static string TruncateString(string str, int length)
        {
            str = Regex.Replace(str, @"<(.|\n)*?>", string.Empty);
            if (str.Length <= length)
            {
                return str;
            }
            else
            {
                int iNextSpace = str.LastIndexOf(" ", length);
                return string.Format("{0}...", str.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
            }
        }

        /// <summary>
        /// delte file
        /// </summary>
        /// <param name="pathFileName"></param>
        /// <returns></returns>
        public static bool DelelteFile(string ServerMapPathFileName)
        {
            if (File.Exists(ServerMapPathFileName))
            {
                File.Delete(ServerMapPathFileName);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// copy file
        /// </summary>
        /// <param name="serverMapPathSourceFile"></param>
        /// <param name="serverMapPathCopy"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool CopyFile(string serverMapPathSourceFile, string serverMapPathCopyDirectory, string filename)
        {
            if (File.Exists(serverMapPathSourceFile) && Directory.Exists(serverMapPathCopyDirectory))
            {
                File.Copy(serverMapPathSourceFile, serverMapPathCopyDirectory + "\\" + filename);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// create ror
        /// </summary>
        /// <param name="saveMapPathROR"></param>
        /// <param name="urlLink"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        public static void CreateROR(string saveMapPathROR, string urlLink, string title, string metaDescription)
        {
            XDocument xDocROR = XDocument.Load(HttpContext.Current.Server.MapPath(saveMapPathROR));
            XNamespace ns2 = "http://rorweb.com/0.1/";
            xDocROR.Root.Element("channel").Add(
                new XElement("item",
                    new XElement("link", HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlLink),
                    new XElement("title", title),
                    new XElement("description", metaDescription),
                    new XElement(ns2 + "updatePeriod", "weekly"),
                    new XElement(ns2 + "sortOrder", "1"),
                    new XElement(ns2 + "resourceOf", "sitemap")));
            xDocROR.Save(HttpContext.Current.Server.MapPath(saveMapPathROR));
        }

        /// <summary>
        /// update ror
        /// </summary>
        /// <param name="saveMapPathROR"></param>
        /// <param name="oldUrlLink"></param>
        /// <param name="newUrllLink"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        public static void UpdateROR(string saveMapPathROR, string oldUrlLink, string newUrllLink, string title, string metaDescription)
        {
            XDocument xDocROR = XDocument.Load(HttpContext.Current.Server.MapPath(saveMapPathROR));
            XElement xEUrl = xDocROR.Descendants("item").Where(ul => ul.Element("link").Value.Trim() == (HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + oldUrlLink).Trim()).FirstOrDefault();
            if (xEUrl != null)
            {
                xEUrl.Element("link").Value = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + newUrllLink;
                xEUrl.Element("title").Value = title;
                xEUrl.Element("description").Value = metaDescription;
                xDocROR.Save(HttpContext.Current.Server.MapPath(saveMapPathROR));
            }
        }

        /// <summary>
        /// delete ROR
        /// </summary>
        /// <param name="saveMapPathROR"></param>
        /// <param name="urlLink"></param>
        public static void DeleteROR(string saveMapPathROR, string urlLink)
        {
            XDocument xDocROR = XDocument.Load(HttpContext.Current.Server.MapPath(saveMapPathROR));
            XElement xEUrl = xDocROR.Descendants("item").Where(ul => ul.Element("link").Value.Trim() == (HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlLink).Trim()).FirstOrDefault();
            if (xEUrl != null)
            {
                xEUrl.Remove();
                xDocROR.Save(HttpContext.Current.Server.MapPath(saveMapPathROR));
            }
        }

        /// <summary>
        /// tao sitemap
        /// </summary>
        /// <param name="saveMapPathSiteMap">duong dan luu sitemap</param>
        /// <param name="urlLoc">url</param>
        public static void CreateSiteMap(string saveMapPathSiteMap, string urlLoc)
        {
            XDocument xDocSiteMap = XDocument.Load(HttpContext.Current.Server.MapPath(saveMapPathSiteMap));
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            xDocSiteMap.Root.Add(
                new XElement(ns + "url",
                    new XElement(ns + "loc", HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlLoc),
                    new XElement(ns + "lastmod", DateTime.Now),
                    new XElement(ns + "changefreq", "weekly"),
                    new XElement(ns + "priority", "0.5")));
            xDocSiteMap.Save(HttpContext.Current.Server.MapPath(saveMapPathSiteMap));
        }

        /// <summary>
        /// update node url sitemap
        /// </summary>
        /// <param name="saveMapPathSiteMap">duong dan luu sitemap</param>
        /// <param name="oldUrlLoc">url cu</param>
        /// <param name="newUrlLoc">url thay the</param>
        public static void UpdateSiteMap(string saveMapPathSiteMap, string oldUrlLoc, string newUrlLoc)
        {
            XDocument xDocSiteMap = XDocument.Load(HttpContext.Current.Server.MapPath(saveMapPathSiteMap));
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            XElement xEUrl = xDocSiteMap.Descendants(ns + "url").Where(ul => ul.Element(ns + "loc").Value.Trim() == (HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + oldUrlLoc).Trim()).FirstOrDefault();
            if (xEUrl != null)
            {
                xEUrl.Element(ns + "loc").Value = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + newUrlLoc;
                xEUrl.Element(ns + "lastmod").Value = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss+00:00");
                xDocSiteMap.Save(HttpContext.Current.Server.MapPath(saveMapPathSiteMap));
            }
        }

        /// <summary>
        /// delete node url sitemap
        /// </summary>
        /// <param name="saveMapPathSiteMap"></param>
        /// <param name="urlLoc"></param>
        public static void DeleteSiteMap(string saveMapPathSiteMap, string urlLoc)
        {
            XDocument xDocSiteMap = XDocument.Load(HttpContext.Current.Server.MapPath(saveMapPathSiteMap));
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            XElement xEUrl = xDocSiteMap.Descendants(ns + "url").Where(ul => ul.Element(ns + "loc").Value.Trim() == (HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlLoc).Trim()).FirstOrDefault();
            if (xEUrl != null)
            {
                xEUrl.Remove();
                xDocSiteMap.Save(HttpContext.Current.Server.MapPath(saveMapPathSiteMap));
            }
        }

        /// <summary>
        /// create urllist
        /// </summary>
        /// <param name="saveMapPathUrlList">duong dan den urllist</param>
        /// <param name="urlNew">them moi 1 url</param>
        public static void CreateUrlList(string saveMapPathUrlList, string urlNew)
        {
            string content = "";
            System.IO.StreamReader StreamReader1 = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(saveMapPathUrlList));
            content = StreamReader1.ReadToEnd();
            StreamReader1.Close();
            content += HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlNew;

            System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(saveMapPathUrlList));
            StreamWriter1.WriteLine(content);
            StreamWriter1.Close();
        }

        /// <summary>
        /// update urllist
        /// </summary>
        /// <param name="saveMapPathUrlList">duong dan den urllist</param>
        /// <param name="urlOld">url cu</param>
        /// <param name="urlNew">url duoc thay the</param>
        public static void UpdateUrlList(string saveMapPathUrlList, string urlOld, string urlNew)
        {
            string content = "";
            System.IO.StreamReader StreamReader1 = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(saveMapPathUrlList));
            content = StreamReader1.ReadToEnd();
            StreamReader1.Close();
            content = Regex.Replace(content, HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlOld, HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlNew);

            System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(saveMapPathUrlList));
            StreamWriter1.Write(content);
            StreamWriter1.Close();
        }

        /// <summary>
        /// delete urllist
        /// </summary>
        /// <param name="saveMapPathUrlList">duong dan den urllist</param>
        /// <param name="urlOld">url muon xoa</param>
        public static void DeleteUrlList(string saveMapPathUrlList, string urlOld)
        {
            string content = "";
            System.IO.StreamReader StreamReader1 = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(saveMapPathUrlList));
            content = StreamReader1.ReadToEnd();
            StreamReader1.Close();
            content = Regex.Replace(content, HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/" + urlOld, string.Empty);

            System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(saveMapPathUrlList));
            StreamWriter1.Write(content);
            StreamWriter1.Close();
        }

        /// <summary>
        /// lay ngay tieng viet
        /// </summary>
        /// <param name="dtt"></param>
        /// <returns></returns>
        public static string GetDayOfWeek(object dtt)
        {
            DateTime dt = Convert.ToDateTime(dtt);
            string thu = dt.DayOfWeek.ToString();
            switch (thu)
            {
                case ("Monday"):
                    return "Thứ Hai";

                case ("Tuesday"):
                    return "Thứ Ba";

                case ("Wednesday"):
                    return "Thứ Tư";

                case ("Thursday"):
                    return "Thứ Năm";

                case ("Friday"):
                    return "Thứ Sáu";

                case ("Saturday"):
                    return "Thứ Bảy";

                default:
                    return "Chủ Nhật";
            }
        }

        /// <summary>
        /// config fckfinder cho fckeditor
        /// </summary>
        /// <param name="ckcontrol"></param>
        public static void CallCKFinder(CKEditor.NET.CKEditorControl ckcontrol)
        {
            CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
            _FileBrowser.BasePath = ApplicationPath + "Plugins/Ckfinder/";
            _FileBrowser.SetupCKEditor(ckcontrol);
        }

        /// <summary>
        /// lay duoi mo rong rewrite
        /// </summary>
        /// <returns></returns>
        public static string GetUrlRewriteExtension()
        {
            XDocument xDocRewrite = XDocument.Load(HttpContext.Current.Server.MapPath(ConfigPaths.Path_Rewrite_Xml));
            XElement xEUrlExtension = xDocRewrite.Descendants("UrlExtension").FirstOrDefault();
            return xEUrlExtension.Value.Trim();
        }

        /// <summary>
        /// lay duong dan rewrite category cua cateid
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="cateID"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewriteCategory(ref DGSFrameworkEntities entity, int cateID, bool toLowerCase)
        {
            string prefix = "";
            string urlCateRewrite = "";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            if (LoopHaveCategory(ref allCate, cateID, ConfigPaths.Category_Article_ID) != 0)
            {
                prefix = "danh-muc-bai-viet/";
            }
            else if (LoopHaveCategory(ref allCate, cateID, ConfigPaths.Category_Product_ID) != 0)
            {
                prefix = "danh-muc-san-pham/";
            }
            else if (LoopHaveCategory(ref allCate, cateID, ConfigPaths.Category_Video_ID) != 0)
            {
                prefix = "danh-muc-video/";
            }
            else
            {
                prefix = "danh-muc-hinh-anh/";
            }
            udv_Categories cate = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
            if (cate != null)
            {
                urlCateRewrite = prefix + FriendlyURL(cate.Title, toLowerCase) + "/" + cate.CateID;
            }
            return urlCateRewrite;
        }

        /// <summary>
        /// lay duong dan rewrite product cua productid
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="productID"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewriteProduct(ref DGSFrameworkEntities entity, int productID, bool toLowerCase)
        {
            string urlProductRewrite = "";
            udv_Products product = entity.udv_Products.Where(pd => pd.ProductID == productID).FirstOrDefault();
            if (product != null)
            {
                urlProductRewrite = "san-pham/" + FriendlyURL(product.Title, toLowerCase) + "/" + productID;
            }
            return urlProductRewrite;
        }

        /// <summary>
        /// lay duong dan rewrite article va articleid
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="articleID"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewriteArticle(ref DGSFrameworkEntities entity, int articleID, bool toLowerCase)
        {
            string urlArticleRewrite = "";
            udv_Articles article = entity.udv_Articles.Where(ar => ar.ArticleID == articleID).FirstOrDefault();
            if (article != null)
            {
                urlArticleRewrite = "bai-viet/" + FriendlyURL(article.Title, toLowerCase) + "/" + articleID;
            }
            return urlArticleRewrite;
        }

        /// <summary>
        /// lay duong dan rewrite video va videoID
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="videoID"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewriteVideo(ref DGSFrameworkEntities entity, int videoID, bool toLowerCase)
        {
            string urlVideoRewrite = "";
            udv_Videos video = entity.udv_Videos.Where(vd => vd.VideoID == videoID).FirstOrDefault();
            if (video != null)
            {
                urlVideoRewrite = "video/" + FriendlyURL(video.Title, toLowerCase) + "/" + videoID;
            }
            return urlVideoRewrite;
        }

        /// <summary>
        /// lay duong dan rewrite photo va photoID
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="PhotoID"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewritePhoto(ref DGSFrameworkEntities entity, int PhotoID, bool toLowerCase)
        {
            string urlPhotoRewrite = "";
            udv_Photos photo = entity.udv_Photos.Where(pt => pt.PhotoID == PhotoID).FirstOrDefault();
            if (photo != null)
            {
                urlPhotoRewrite = "hinh-anh/" + FriendlyURL(photo.Title, toLowerCase) + "/" + PhotoID;
            }
            return urlPhotoRewrite;
        }

        /// <summary>
        /// lay tat ca duong dan rewrite cua cac category gallery image con cua cateid cha va cate cha
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="cateID"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewriteCategoryGalleryImage(ref DGSFrameworkEntities entity, int cateID, bool toLowerCase)
        {
            string allUrlCateRewrite = "";
            udv_CateGalleryImage cate = entity.udv_CateGalleryImage.Where(ca => ca.CateID == cateID).FirstOrDefault();
            if (cate != null)
            {
                allUrlCateRewrite = FriendlyURL(cate.Title, toLowerCase) + "/" + cate.CateID;
            }
            return allUrlCateRewrite;
        }

        /// <summary>
        /// tao urlRewrite ngoai le
        /// </summary>
        /// <param name="prefixRewrite"></param>
        /// <param name="title"></param>
        /// <param name="id"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string CreateUrlRewriteOrther(string prefixRewrite, string title, int id, bool toLowerCase)
        {
            return toLowerCase == true ? prefixRewrite.ToLower() + "/" + FriendlyURL(title, toLowerCase) + "/" + id : prefixRewrite + "/" + FriendlyURL(title, toLowerCase) + "/" + id;
        }

        /// <summary>
        /// kiem tra co rewrite hay ko
        /// </summary>
        /// <returns></returns>
        public static bool CheckRewriteUrl()
        {
            XDocument xDocRewrite = XDocument.Load(HttpContext.Current.Server.MapPath(ConfigPaths.Path_Rewrite_Xml));
            XElement XEEnable = xDocRewrite.Descendants("Enable").FirstOrDefault();
            if (XEEnable.Value.Trim() == "0")
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// lay url aspx hay rewrite theo file cau hinh rewrite
        /// </summary>
        /// <param name="rewriteUrl"></param>
        /// <param name="aspxUrl"></param>
        /// <returns></returns>
        public static string GetUrl(string rewriteUrl, string aspxUrl)
        {
            XDocument xDocRewrite = XDocument.Load(HttpContext.Current.Server.MapPath(ConfigPaths.Path_Rewrite_Xml));
            XElement XEEnable = xDocRewrite.Descendants("Enable").FirstOrDefault();
            if (XEEnable.Value.Trim() == "0")
            {
                return aspxUrl;
            }
            else
            {
                return rewriteUrl + GetUrlRewriteExtension();
            }
        }

        /// <summary>
        /// Tim ra url aspx dựa vao url rewrite, có chưa query string
        /// </summary>
        /// <param name="urlRewrite"></param>
        /// <returns></returns>
        public static string GetUrlAspx(string urlRewrite, bool category)
        {
            if (urlRewrite.Contains("bai-viet/"))
            {
                return category == true ? "Articles.aspx?CateID=" : "ArticleDetails.aspx?ArticleID=";
            }
            else if (urlRewrite.Contains("san-pham/"))
            {
                return category == true ? "Products.aspx?CateID=" : "ProductDetails.aspx?ProductID=";
            }
            else if (urlRewrite.Contains("video/"))
            {
                return category == true ? "Videos.aspx?CateID=" : "VideoDetails.aspx?VideoID=";
            }
            else
            {
                return category == true ? "Photos.aspx?CateID=" : "PhotoDetails.aspx?PhotoID=";
            }
        }

        /// <summary>
        /// Tim ra url aspx dua vao url rewrite
        /// </summary>
        /// <param name="urlRewrite"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string GetUrlAspxNoneQueryString(string urlRewrite, bool category)
        {
            if (urlRewrite.Contains("bai-viet/"))
            {
                return category == true ? "Articles.aspx" : "ArticleDetails.aspx";
            }
            else if (urlRewrite.Contains("san-pham/"))
            {
                return category == true ? "Products.aspx" : "ProductDetails.aspx";
            }
            else if (urlRewrite.Contains("video/"))
            {
                return category == true ? "Videos.aspx" : "VideoDetails.aspx";
            }
            else
            {
                return category == true ? "Photos.aspx" : "PhotoDetails.aspx";
            }
        }

        /// <summary>
        /// tim Category cha co giong voi cateid truyen vao hay ko
        /// </summary>
        /// <param name="categories">tat ca cac category</param>
        /// <param name="ParentCateID">category id can tim</param>
        /// <param name="cateID">category id can so sanh</param>
        /// <returns></returns>
        public static int LoopHaveCategory(ref List<udv_Categories> categories, int cateID, int ParentCateID)
        {
            int haveCate = 0;
            if (cateID == ParentCateID)
            {
                haveCate = cateID;
                return haveCate;
            }
            var cateChild = categories.Where(c => c.ParentID == ParentCateID).ToList();
            foreach (var item in cateChild)
            {
                if (item.CateID == cateID)
                {
                    haveCate = item.CateID;
                    return haveCate;
                }
                else
                {
                    haveCate += LoopHaveCategory(ref categories, cateID, item.CateID);
                }
            }
            return haveCate;
        }

        /// <summary>
        /// tim Category cha co giong voi cateid truyen vao hay ko
        /// </summary>
        /// <param name="categories">tat ca cac category</param>
        /// <param name="ParentCateID">category id can tim</param>
        /// <param name="cateID">category id can so sanh</param>
        /// <returns></returns>
        public static int LoopHaveCategory(ref List<udv_Categories> categories, int cateID, int ParentCateID, bool isActive)
        {
            int haveCate = 0;
            if (cateID == ParentCateID)
            {
                haveCate = cateID;
                return haveCate;
            }
            var cateChild = categories.Where(c => c.ParentID == ParentCateID && c.IsActive == isActive).ToList();
            foreach (var item in cateChild)
            {
                if (item.CateID == cateID)
                {
                    haveCate = item.CateID;
                    return haveCate;
                }
                else
                {
                    haveCate += LoopHaveCategory(ref categories, cateID, item.CateID, isActive);
                }
            }
            return haveCate;
        }

        /// <summary>
        /// lay tat ca cac category con cua categoryid cha
        /// </summary>
        /// <param name="categories">tat ca cac category</param>
        /// <param name="cateID">cateid cha</param>
        /// <returns></returns>
        public static List<udv_Categories> LoopGetCategories(ref List<udv_Categories> categories, int cateID)
        {
            var cateChild = categories.Where(c => c.ParentID == cateID && c.IsActive == true).ToList();
            foreach (var item in cateChild)
            {
                cateChild = cateChild.Union(LoopGetCategories(ref categories, item.CateID)).ToList();
            }
            return cateChild;
        }

        /// <summary>
        /// lay tat ca cac category con cua categoryid cha
        /// </summary>
        /// <param name="categories">tat ca cac category</param>
        /// <param name="cateID">cateid cha</param>
        /// <returns></returns>
        public static List<udv_Categories> LoopGetCategories(ref List<udv_Categories> categories, int cateID, bool isActive)
        {
            var cateChild = categories.Where(c => c.ParentID == cateID && c.IsActive == isActive).ToList();
            foreach (var item in cateChild)
            {
                cateChild = cateChild.Union(LoopGetCategories(ref categories, item.CateID, isActive)).ToList();
            }
            return cateChild;
        }

        //nhathn bo sung cho hien thi menucontext
        public static string GetMenuContext(string userName, string type, string[] roles, List<dgs_Favorite> fav)
        {
            var language = "";
            if (HttpContext.Current.Session["language"] != null)
                language = HttpContext.Current.Session["language"].ToString();
            var lblAddTo = "Thêm vào";
            var lblMoveTo = "Di chuyển đến";
            var lblDelete = "Xóa";
            if(language.Equals("en-US"))
            {
                lblAddTo = "Add to";
                lblMoveTo = "Move to";
                lblDelete = "Delete";
            }
            StringBuilder sb = new StringBuilder();
            var isViewFav = type.IndexOf(MenuType.myfavorite.ToString()) >= 0;//dung de kiem tra dang xem danh sach fav hay ko;
            sb.Append("<ul class='contextMenu'>");
            if (userName.Equals("MasterDK")||userName.Equals("uyenadmin"))
            {
                //an theo yeu cau cua DK
                //sb.Append("<li class='deletestock'><img src='/images/delicon.png' style='width:15px' />" + " Delete from list" + "</li>");
                sb.Append("<li><img src='/images/add.png' style='width:15px' />" + lblAddTo);

                sb.Append("<ul class='open'>");
                if (isViewFav)
                {
                    var favID = int.Parse((type.Split('_'))[1]);
                    var favRemove = fav.Where(d => d.FavID == favID).SingleOrDefault();
                    if (favRemove != null)
                        fav.Remove(favRemove);
                }
                foreach (var item in fav)
                {
                    sb.Append("<li class='add2fav' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
                }
                sb.Append("</ul></li>");
                if (isViewFav)
                {
                    sb.Append("<li class='deletefavitem'><img src='/images/delicon.png' style='width:15px' /> "+lblDelete+"</li>");
                    sb.Append("<li><img src='/images/moveicon.png' style='width:15px' /> " + lblMoveTo + "<ul class='open'>");
                    foreach (var item in fav)
                    {
                        sb.Append("<li class='movestock' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
                    }
                    sb.Append("</ul></li>");
                }
                if (type == MenuType.watchlistbuy.ToString())
                {
                    sb.Append("<li class='deletebuy'>" + "Delete from watchlist buy" + "</li>");
                    sb.Append("<li class='addsell'><img src='/images/add.png' style='width:15px' /> Add to watchlist sell</li>");
                }
                else if (type == MenuType.watchlistsell.ToString())
                {
                    sb.Append("<li class='deletesell'>" + "Delete from watchlist sell" + "</li>");
                    sb.Append("<li class='addbuy'><img src='/images/add.png' style='width:15px' /> Add to watchlist buy</li>");
                }
                else
                {
                    sb.Append("<li class='addbuy'><img src='/images/add.png' style='width:15px' /> Add to watchlist buy</li>");
                    sb.Append("<li class='addsell'> <img src='/images/add.png' style='width:15px' /> Add to watchlist sell</li>");
                }
            }
            else
            {
                if (isViewFav)
                {
                    var currentID=int.Parse((type.Split('_')[1]));
                    if (fav.Where(d => d.FavID == currentID).Count() > 0) // xu ly khi o trong danh sach fav cua tai khoan
                    {
                        sb.Append("<li><img src='/images/add.png' style='width:15px' /> " + lblAddTo);
                        sb.Append("<ul class='open'>");
                        foreach (var item in fav)
                        {
                            sb.Append("<li class='add2fav' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
                        }
                        sb.Append("</ul></li>");
                        sb.Append("<li><img src='/images/moveicon.png' style='width:15px' /> "+lblMoveTo+"<ul class='open'>");
                        foreach (var item in fav)
                        {
                            sb.Append("<li class='movestock' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
                        }
                        sb.Append("</ul></li>");
                        sb.Append("<li class='deletefavitem'><img src='/images/delicon.png' style='width:15px' /> "+lblDelete+"</li>");
                    }
                    else
                    {
                        sb.Append("<li><img src='/images/add.png' style='width:15px' /> " + lblAddTo);
                        sb.Append("<ul class='open'>");
                        foreach (var item in fav)
                        {
                            sb.Append("<li class='add2fav' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
                        }
                        sb.Append("</ul></li>");
                    }
                }
                else
                {
                    sb.Append("<li><img src='/images/add.png' style='width:15px' /> " +lblAddTo);
                    sb.Append("<ul class='open'>");
                    foreach (var item in fav)
                    {
                        sb.Append("<li class='add2fav' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
                    }
                    sb.Append("</ul></li>");
                }


                //sb.Append("<li>" + "Add to");
                //sb.Append("<ul class='open'>");
                //if (isViewFav)
                //{
                //    var favID = int.Parse((type.Split('_'))[1]);
                //    var favRemove = fav.Where(d => d.FavID == favID).SingleOrDefault();
                //    if (favRemove != null)
                //        fav.Remove(favRemove);
                //}
                

                //if (isViewFav)
                //{
                //    sb.Append("<li class='deletefavitem'>Delete</li>");
                    
                //}
            }


            //if (userName == "MasterDK")
            //    sb.Append("<li class=\"deletestock\">" + "Delete from system" + "</li>");
            //if (fav.Count() > 0)
            //{
            //    sb.Append("<li>" + "Add to");
            //    sb.Append("<ul class=\"open\">");
            //    if (isViewFav)
            //    {
            //        var favID = int.Parse((type.Split('_'))[1]);
            //        var favRemove = fav.Where(d => d.FavID == favID).SingleOrDefault();
            //        if (favRemove != null)
            //            fav.Remove(favRemove);
            //    }
            //    foreach (var item in fav)
            //    {
            //        sb.Append("<li class=\"add2fav\" data-favid=\"" + item.FavID + "\">" + item.FavName + "</li>");
            //    }
            //    sb.Append("</ul></li>");
            //}
            //if (isViewFav)
            //{
            //    if (userName == "MasterDK")
            //    {
            //        sb.Append("<li class='deletefavitem'>Delete</li>");
            //        if (fav.Count() > 0)
            //        {
            //            var favID = int.Parse((type.Split('_'))[1]);
            //            var favRemove = fav.Where(d => d.FavID == favID).SingleOrDefault();
            //            if (favRemove != null)
            //                fav.Remove(favRemove);
            //            if (fav.Count() > 0)
            //            {
            //                sb.Append("<li>Move to<ul class=\"open\">");
            //                foreach (var item in fav)
            //                {
            //                    sb.Append("<li class='movestock' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
            //                }
            //                sb.Append("</ul></li>");
            //            }
            //        }
            //        sb.Append("<li class=\"addbuy\">Add to watchlist buy</li>");
            //        sb.Append("<li class=\"addsell\">Add to watchlist sell</li>");
            //    }
            //    else //chi hien xoa item trong fav cua user
            //    {
            //        var favID = int.Parse((type.Split('_'))[1]);
            //        if (fav.Where(d => d.FavID == favID).Count() > 0)
            //        {
            //            sb.Append("<li class='deletefavitem'>Delete</li>");
            //            if (fav.Count() > 0)
            //            {
            //                var favRemove = fav.Where(d => d.FavID == favID).SingleOrDefault();
            //                if (favRemove != null)
            //                    fav.Remove(favRemove);
            //                if (fav.Count() > 0)
            //                {
            //                    sb.Append("<li>Move to<ul class=\"open\">");
            //                    foreach (var item in fav)
            //                    {
            //                        sb.Append("<li class='movestock' data-favid='" + item.FavID + "'>" + item.FavName + "</li>");
            //                    }
            //                    sb.Append("</ul></li>");
            //                }
            //            }
            //        }
            //    }

            //}
            //else if (type == MenuType.watchlistbuy.ToString() && userName == "MasterDK")
            //{
            //    sb.Append("<li class=\"deletebuy\">" + "Delete from watchlist buy" + "</li>");
            //}
            //else if (type == MenuType.watchlistsell.ToString() && userName == "MasterDK")
            //{
            //    sb.Append("<li class=\"deletesell\">" + "Delete from watchlist sell" + "</li>");
            //}
            //if (userName == "MasterDK" && (type == MenuType.allstock.ToString() || type == MenuType.topvolume.ToString() || type == MenuType.topgainer.ToString() || type == MenuType.toploser.ToString() || type == MenuType.topactive.ToString()))
            //{
            //    sb.Append("<li class=\"addbuy\">Add to watchlist buy</li>");
            //    sb.Append("<li class=\"addsell\">Add to watchlist sell</li>");
            //}
            sb.Append("</ul>");
            return sb.ToString();
        }

        public static string GetDropdownMenu(string userName, string[] roles, List<dgs_Favorite> userFav)
        {
            var language = "";
            if (HttpContext.Current.Session["language"] != null)
                language = HttpContext.Current.Session["language"].ToString();
            var lblAllStock = "Danh sách cổ phiếu";
            var lblTopVolume = "Top KLGD";
            var lblTopGainer = "Top tăng giá";
            var lblTopLoser = "Top giảm giá";
            var lblTopActive = "Top khớp lệnh";
            var lblNewFolder = "Thư mục mới";
            var lblWatchlistBuy = "Watchlist - mua";
            var lblWatchlistSell = "Watchlist - bán";
            if (language.Equals("en-US"))
            {
                lblAllStock = "All stock";
                lblTopVolume = "Top volume";
                lblTopGainer = "Top gainer";
                lblTopLoser = "Top loser";
                lblTopActive = "Top Active";
                lblNewFolder = "New Folder";
                lblWatchlistBuy = "Watchlist - buy";
                lblWatchlistSell = "Watchlist - sell";
            }

            var sb = new StringBuilder();
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            var masterFav = entity.dgs_Favorite.Where(d => d.udv_Users.UserName == "MasterDK" || d.udv_Users.UserName == "uyenadmin");
            sb.Append("<li><a href='#' data-id='AllStock'>"+lblAllStock+"</a></li>");
            sb.Append("<li><a href='#' data-id='TopVolume'>"+lblTopVolume+"</a></li>");
            sb.Append("<li><a href='#' data-id='TopGainer'>"+lblTopGainer+"</a></li>");
            sb.Append("<li><a href='#' data-id='TopLoser'>"+lblTopLoser+"</a></li>");
            sb.Append("<li><a href='#' data-id='TopActive'>"+lblTopActive+"</a></li>");
            if (userName != "MasterDK" && userName != "uyenadmin")
            {
                foreach (var item in masterFav)
                {
                    sb.Append("<li><a href='#' data-id='myfavorite_" + item.FavID + "'>" + (language.Equals("en-US")? item.FavName_en: item.FavName)+ "</a></li>");
                }
            }
            sb.Append("<li><a href='#' data-id='newfolder'><img src='../images/folder.png' style='width: 15px;' /> "+lblNewFolder+"</a>");
            if (userFav != null && userFav.Count() > 0)
            {
                sb.Append("<ul class='open'>");
                foreach (var item in userFav)
                {
                    sb.Append("<li><img src='../images/folder.png' style='width: 15px;'/> <a href='#' data-id='myfavorite_" + item.FavID + "'>" + item.FavName + "</a></li>");
                }
                sb.Append("</ul>");
            }
            sb.Append("</li>");
            if (userName == "MasterDK" || roles.Contains("Plan A")||userName.Equals("uyenadmin"))
            {
                sb.Append("<li><a href='#' data-id='watchlistbuy'>" + lblWatchlistBuy + "</a></li>");
                sb.Append("<li><a href='#' data-id='watchlistsell'>" + lblWatchlistSell + "</a></li>");
            }
            else
            {
                sb.Append("<li><a href='#' data-id='view'>" + lblWatchlistBuy + "</a></li>");
                sb.Append("<li><a href='#' data-id='view'>" + lblWatchlistSell + "</a></li>");
            }
            return sb.ToString();
        }
    }

    public class SendMail
    {
        public SendMail()
        {
            _mailMessage = new System.Net.Mail.MailMessage();
        }

        private string yourMail;
        public string YourMailAccount
        {
            get { return yourMail; }
            set { yourMail = value; }
        }

        private string yourPassword;
        public string YourMailPassword
        {
            get { return yourPassword; }
            set { yourPassword = value; }
        }

        private string serverPort;
        public string ServerPort
        {
            set { serverPort = value; }
            get { return serverPort; }
        }

        private string serverMail;
        public string ServerMail
        {
            get { return serverMail; }
            set { serverMail = value; }
        }

        private bool ssl;
        public bool SSL
        {
            get { return ssl; }
            set { ssl = value; }
        }

        private MailMessage _mailMessage;

        /// <summary>
        /// Xác định server mail được sử dụng.
        /// </summary>
        /// <param name="UrMail">Địa chỉ mail của bạn.</param>
        /// <returns></returns>
        public void SetUpYourServerMail()
        {
            //_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", YourMailAccount);
            //_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", YourMailPassword);
            //_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", ServerPort);
            //_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
        }

        /// <summary>
        /// Tạo đối tượng MailMessage.
        /// </summary>
        /// <param name="receiver">Địa chỉ mail người nhận.</param>
        /// <param name="content">Nội dung bức mail.</param>
        /// <param name="Subject">chủ đề của bức mail.</param>
        /// <returns></returns>
        public void CreateMailObject(string receiver, string content, string Subject, string bcc)
        {
            _mailMessage.To.Add(receiver);
            if (!string.IsNullOrEmpty(bcc))
                _mailMessage.Bcc.Add(bcc);
            _mailMessage.From = new MailAddress(YourMailAccount);
            _mailMessage.Body = content;
            _mailMessage.IsBodyHtml = true;
            _mailMessage.Subject = Subject;
            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            _mailMessage.Priority = MailPriority.Normal;
        }

        public bool MailSending()
        {
            System.Net.Mail.SmtpClient smtpC = new System.Net.Mail.SmtpClient(serverMail, int.Parse(ServerPort));
            smtpC.EnableSsl = SSL;
            smtpC.UseDefaultCredentials = false;
            smtpC.Credentials = new NetworkCredential(YourMailAccount, YourMailPassword);

            try
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s,
                    System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };
                smtpC.Send(_mailMessage);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

    public class ProductShoppingCart
    {
        public int ProductID { get; set; }
        public string ProductCode { get; set; }
        public string Title { get; set; }
        public string Title_en { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal SalePrice { get; set; }
        public decimal PromotionPrice { get; set; }
        public int PromotionPercent { get; set; }
        public string ImageUrl { get; set; }
        public int Quantity { get; set; }
    }

    public class ShoppingCart
    {
        public List<ProductShoppingCart> Items { get; set; }

        /// <summary>
        /// khoi tao shopping cart
        /// </summary>
        public static ShoppingCart Cart
        {
            get
            {
                var cart = HttpContext.Current.Session["Cart"];
                if (cart == null) // chưa có trong session
                {
                    // tạo mới
                    cart = new ShoppingCart
                    {
                        Items = new List<ProductShoppingCart>()
                    };
                    // lưu vào session
                    HttpContext.Current.Session["Cart"] = cart;
                }
                return (ShoppingCart)cart;
            }
        }

        /// <summary>
        /// tong so san pham trong cart
        /// </summary>
        public int Count
        {
            get
            {
                if (Items == null || Items.Count == 0)
                {
                    return 0;
                }
                else
                {
                    return Items.Count;
                }
            }
        }

        /// <summary>
        /// lấy tổng số tiền trong giỏ hàng
        /// </summary>
        public decimal TotalAmount
        {
            get
            {
                if (Items == null || Items.Count == 0)
                {
                    return 0;
                }
                else
                {
                    return Items.Sum(pr => (pr.PromotionPrice == 0 ? pr.SalePrice : pr.PromotionPrice) * pr.Quantity);
                }
            }
        }

        /// <summary>
        /// lay tong tien 1 loai san pham
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public decimal Amount(ProductShoppingCart product)
        {
            ProductShoppingCart item = Items.Where(pr => pr.ProductID == product.ProductID).FirstOrDefault();
            if (item == null)
            {
                return 0;
            }
            else
            {
                return (item.PromotionPrice == 0 ? item.SalePrice : item.PromotionPrice) * item.Quantity;
            }
        }

        /// <summary>
        /// them 1 san pham vao gio hang
        /// </summary>
        /// <param name="product"></param>
        public void Add(ProductShoppingCart product)
        {
            ProductShoppingCart item = Items.Where(pr => pr.ProductID == product.ProductID).FirstOrDefault();
            if (item == null)
            {
                item = product;
                product.Quantity = 1;
                Items.Add(item);
            }
            else
            {
                item.Quantity++;
            }
        }

        /// <summary>
        /// Xóa 1 sản phẩm khỏi giỏ hàng
        /// </summary>
        /// <param name="product"></param>
        public void Remove(ProductShoppingCart product)
        {
            ProductShoppingCart item = Items.Where(pr => pr.ProductID == product.ProductID).FirstOrDefault();
            if (item != null)
            {
                Items.Remove(item);
            }
        }

        /// <summary>
        /// cập nhật số lượng của hàng hóa
        /// </summary>
        /// <param name="product"></param>
        /// <param name="newQuantity"></param>
        public void Update(int? newQuantity, ProductShoppingCart product)
        {
            //Product prod = Items.Single(p => p.Id == id);
            //prod.Quantity = newQuantity;
            ProductShoppingCart item = Items.Where(pr => pr.ProductID == product.ProductID).FirstOrDefault();
            if (item != null && newQuantity != null && newQuantity > 0)
            {
                item.Quantity = newQuantity.Value;
            }
            else if (item != null && newQuantity == null)
            {
                item.Quantity++;
            }
        }

        /// <summary>
        /// xóa sạch giỏ hàng
        /// </summary>
        public void Clear()
        {
            Items.Clear();
        }
    }

    public enum TypeAction
    {
        None = 1,
        Insert = 2,
        Update = 3,
        Delete = 4
    }

    public enum TypePost
    {
        Article = 1,
        Product = 2,
        Photo = 3,
        Video = 4
    }
    /// <summary>
    /// combobox menutype trang 2
    /// </summary>
    public enum MenuType
    {
        allstock, topvolume, topgainer, toploser, topactive, myfavorite, watchlistbuy, watchlistsell
    }
}
